#!/usr/bin/env node

/**
 * HTTP响应标准化工具自检脚本
 * 运行: node scripts/self-check-http-normalize.mjs
 */

import { normalizeResponse, normalizeAxiosError } from '../src/utils/http-normalize.js'

// 测试用例计数
let totalTests = 0
let passedTests = 0

// 测试工具函数
function test(name, testFn) {
  totalTests++
  try {
    testFn()
    console.log(`✅ PASS: ${name}`)
    passedTests++
  } catch (error) {
    console.log(`❌ FAIL: ${name}`)
    console.log(`   Error: ${error.message}`)
  }
}

function assertEquals(actual, expected, message = '') {
  if (actual !== expected) {
    throw new Error(`Expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}. ${message}`)
  }
}

function assertNull(actual, message = '') {
  if (actual !== null) {
    throw new Error(`Expected null, got ${JSON.stringify(actual)}. ${message}`)
  }
}

function assertThrows(fn, expectedMessage = '') {
  try {
    fn()
    throw new Error('Expected function to throw an error')
  } catch (error) {
    if (expectedMessage && !error.message.includes(expectedMessage)) {
      throw new Error(`Expected error message to contain "${expectedMessage}", got "${error.message}"`)
    }
  }
}

function assertDeepEquals(actual, expected, message = '') {
  if (JSON.stringify(actual) !== JSON.stringify(expected)) {
    throw new Error(`Expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}. ${message}`)
  }
}

console.log('🔍 开始HTTP响应标准化工具自检...\n')

// 测试用例A：Content-Length为0的空响应
test('A: Content-Length为0的空响应应返回null', () => {
  const response = {
    status: 200,
    headers: { 'content-length': '0' },
    data: ''
  }
  const result = normalizeResponse(response)
  assertNull(result)
})

// 测试用例B：204状态码应返回null
test('B: 204状态码应返回null', () => {
  const response = {
    status: 204,
    headers: {},
    data: ''
  }
  const result = normalizeResponse(response)
  assertNull(result)
})

// 测试用例C：data为null应返回null
test('C: data为null应返回null', () => {
  const response = {
    status: 200,
    headers: { 'content-type': 'application/json' },
    data: null
  }
  const result = normalizeResponse(response)
  assertNull(result)
})

// 测试用例D：JSON包裹格式成功响应应返回业务数据
test('D: JSON包裹格式成功响应应返回业务数据', () => {
  const response = {
    status: 200,
    headers: { 'content-type': 'application/json' },
    data: { code: 200, data: { ok: 1 } }
  }
  const result = normalizeResponse(response)
  assertDeepEquals(result, { ok: 1 })
})

// 测试用例E：JSON包裹格式失败响应应抛出错误
test('E: JSON包裹格式失败响应应抛出错误', () => {
  const response = {
    status: 200,
    headers: { 'content-type': 'application/json' },
    data: { code: 500, msg: '失败' }
  }
  assertThrows(() => normalizeResponse(response), '失败')
})

// 测试用例F：Blob响应应直接返回数据
test('F: Blob响应应直接返回数据', () => {
  const blobData = new Uint8Array([1, 2])
  const response = {
    status: 200,
    request: { responseType: 'blob' },
    data: blobData
  }
  const result = normalizeResponse(response)
  assertEquals(result, blobData)
})

// 测试用例G：HTTP 500应抛出错误
test('G: HTTP 500应抛出错误', () => {
  const response = {
    status: 500,
    data: 'err'
  }
  assertThrows(() => normalizeResponse(response), 'HTTP 500')
})

// 额外测试：normalizeAxiosError函数
test('额外: normalizeAxiosError应正确处理axios错误', () => {
  const axiosError = {
    response: {
      status: 404,
      data: { msg: '资源未找到' }
    },
    config: {
      url: '/api/test'
    }
  }
  const result = normalizeAxiosError(axiosError)
  assertEquals(result.message, 'HTTP 404: 资源未找到')
  assertEquals(result.status, 404)
  assertEquals(result.url, '/api/test')
})

// 额外测试：支持不同的成功状态码
test('额外: 支持code为200000的成功响应', () => {
  const response = {
    status: 200,
    headers: { 'content-type': 'application/json' },
    data: { code: 200000, data: { success: true } }
  }
  const result = normalizeResponse(response)
  assertDeepEquals(result, { success: true })
})

// 额外测试：支持原生JSON响应
test('额外: 原生JSON响应应直接返回', () => {
  const response = {
    status: 200,
    headers: { 'content-type': 'application/json' },
    data: { name: 'test', value: 123 }
  }
  const result = normalizeResponse(response)
  assertDeepEquals(result, { name: 'test', value: 123 })
})

// 输出测试结果
console.log(`\n📊 测试结果: PASS ${passedTests}/${totalTests}`)

if (passedTests === totalTests) {
  console.log('🎉 所有测试通过！HTTP响应标准化工具工作正常。')
  process.exit(0)
} else {
  console.log('💥 部分测试失败，请检查代码实现。')
  process.exit(1)
}
